package com.smartcampusbackend.controller;

import com.smartcampusbackend.model.CommunityPost;
import com.smartcampusbackend.model.PostComment;

import com.smartcampusbackend.model.User;
import com.smartcampusbackend.service.CommunityPostService;
import com.smartcampusbackend.service.TokenService;
import com.smartcampusbackend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.util.StringUtils;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jakarta.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/api/community-post")
@CrossOrigin(origins = "*")
public class CommunityPostController {

    @Autowired
    private CommunityPostService postService;
    
    @Autowired
    private TokenService tokenService;
    
    @Autowired
    private UserService userService;

    // 获取当前登录用户信息
    private Integer getCurrentUserId(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            String username = tokenService.getUsernameByToken(token);
            if (username != null) {
                User user = userService.getByUsername(username);
                return user != null ? user.getId() : null;
            }
        }
        return null;
    }

    // 发布帖子
    @PostMapping("/create")
    public ResponseEntity<?> createPost(
            @RequestBody CommunityPost post,
            HttpServletRequest request) {
        try {
            Integer userId = getCurrentUserId(request);
            if (userId == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 401);
                response.put("message", "用户未登录");
                response.put("data", null);
                return ResponseEntity.status(401).body(response);
            }

            CommunityPost created = postService.createPost(post, userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "帖子发布成功");
            response.put("data", created);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", e.getMessage());
            response.put("data", null);
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 删除帖子
    @DeleteMapping("/{postId}")
    public ResponseEntity<?> deletePost(
            @PathVariable Integer postId,
            HttpServletRequest request) {
        try {
            Integer userId = getCurrentUserId(request);
            if (userId == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 401);
                response.put("message", "用户未登录");
                response.put("data", null);
                return ResponseEntity.status(401).body(response);
            }
            String token = request.getHeader("Authorization");
            String username = null;
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
                username = tokenService.getUsernameByToken(token);
            }
            User user = userService.getByUsername(username);
            boolean isAdmin = user != null && "ADMIN".equals(user.getRole());
            boolean success = postService.deletePost(postId, userId, isAdmin);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "帖子删除成功");
            response.put("data", null);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", e.getMessage());
            response.put("data", null);
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 获取社群的所有帖子
    @GetMapping("/community/{communityId}")
    public ResponseEntity<?> getCommunityPosts(@PathVariable Integer communityId) {
        try {
            List<CommunityPost> posts = postService.getCommunityPosts(communityId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "获取帖子列表成功");
            response.put("data", posts);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", e.getMessage());
            response.put("data", null);
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 获取帖子详情
    @GetMapping("/{postId}")
    public ResponseEntity<?> getPostDetail(@PathVariable Integer postId) {
        try {
            CommunityPost post = postService.getPostDetail(postId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "获取帖子详情成功");
            response.put("data", post);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", e.getMessage());
            response.put("data", null);
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 点赞/取消点赞帖子
    @PostMapping("/{postId}/like")
    public ResponseEntity<?> togglePostLike(
            @PathVariable Integer postId,
            HttpServletRequest request) {
        try {
            Integer userId = getCurrentUserId(request);
            if (userId == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 401);
                response.put("message", "用户未登录");
                response.put("data", null);
                return ResponseEntity.status(401).body(response);
            }

            boolean success = postService.togglePostLike(postId, userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "操作成功");
            response.put("data", success);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", e.getMessage());
            response.put("data", null);
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 发布评论
    @PostMapping("/comment")
    public ResponseEntity<?> createComment(
            @RequestBody PostComment comment,
            HttpServletRequest request) {
        try {
            Integer userId = getCurrentUserId(request);
            if (userId == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 401);
                response.put("message", "用户未登录");
                response.put("data", null);
                return ResponseEntity.status(401).body(response);
            }

            PostComment created = postService.createComment(comment, userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "评论发布成功");
            response.put("data", created);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", e.getMessage());
            response.put("data", null);
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 删除评论
    @DeleteMapping("/comment/{commentId}")
    public ResponseEntity<?> deleteComment(
            @PathVariable Integer commentId,
            HttpServletRequest request) {
        try {
            Integer userId = getCurrentUserId(request);
            if (userId == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 401);
                response.put("message", "用户未登录");
                response.put("data", null);
                return ResponseEntity.status(401).body(response);
            }

            boolean success = postService.deleteComment(commentId, userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "评论删除成功");
            response.put("data", null);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", e.getMessage());
            response.put("data", null);
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 获取帖子的所有评论
    @GetMapping("/{postId}/comments")
    public ResponseEntity<?> getPostComments(@PathVariable Integer postId) {
        try {
            List<PostComment> comments = postService.getPostComments(postId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "获取评论列表成功");
            response.put("data", comments);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", e.getMessage());
            response.put("data", null);
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 点赞/取消点赞评论
    @PostMapping("/comment/{commentId}/like")
    public ResponseEntity<?> toggleCommentLike(
            @PathVariable Integer commentId,
            HttpServletRequest request) {
        try {
            Integer userId = getCurrentUserId(request);
            if (userId == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 401);
                response.put("message", "用户未登录");
                response.put("data", null);
                return ResponseEntity.status(401).body(response);
            }

            boolean success = postService.toggleCommentLike(commentId, userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "操作成功");
            response.put("data", success);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", e.getMessage());
            response.put("data", null);
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 图片上传接口（多图）
    @PostMapping("/upload-image")
    public ResponseEntity<?> uploadImages(@RequestParam("files") MultipartFile[] files) {
        ArrayList<String> urls = new ArrayList<>();
        // 获取uploads/community-post/的绝对路径，保证和静态资源映射一致
        String uploadDir = new File("uploads/community-post/").getAbsolutePath() + File.separator;
        File dir = new File(uploadDir);
        if (!dir.exists()) dir.mkdirs();
        for (MultipartFile file : files) {
            if (!file.isEmpty()) {
                String originalFilename = file.getOriginalFilename();
                String ext = StringUtils.getFilenameExtension(originalFilename);
                String newName = System.currentTimeMillis() + "_" + (int)(Math.random()*10000) + "." + ext;
                File dest = new File(dir, newName);
                try {
                    file.transferTo(dest);
                    urls.add("/uploads/community-post/" + newName);
                } catch (IOException e) {
                    return ResponseEntity.badRequest().body("图片上传失败: " + e.getMessage());
                }
            }
        }
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "上传成功");
        response.put("data", urls);
        return ResponseEntity.ok(response);
    }

} 